import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
declare var Viewer: any;
declare var BMap: any;
declare var toWGS84: any;
declare var toWGS84Arr: any;
declare var toMapPointArr: any;

@Component({
    selector: 'sa-tunnel-marking',
    templateUrl: './tunnel-marking.component.html',
    styleUrls: ['./tunnel-marking.css']
})
export class TunnelMarkingComponent implements OnInit {
    tableData: any[] = []; //table数据
    totalCount: number = 0; //分页总条数
    curPage: number = 1; //分页当前页
    pageSize: number = 10; //内置的分页每页条数
    tableParam: any = {
        tunnelMarkName: '',
        searchKey: '',
    }

    constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
        activatedRoute.queryParams.subscribe(queryParams => {
            this.curPage = queryParams.nowPage || 1;
        });
    }
    ngOnInit() {
        this.load();
        this.initMap();
        this.initDrawingStyle();
    }
    //table刷新
    refresh() {
        this.load();
    }
    //表格搜索
    tableSearch() {
        this.curPage = 1;
        this.load();
    }
    //分页回调
    paginate(e) {
        this.curPage = e.page + 1;
        this.pageSize = e.rows;
        this.load();
    }
    //初始化加载list数据
    load() {
        let data = {
            pageSize: this.pageSize,
            nowPage: this.curPage,
            parameters: {
//              tunnelMarkName: common.stringTrim(this.tableParam.tunnelMarkName),
                searchKey: common.stringTrim(this.tableParam.searchKey),
            }
        }
        let reqdata = 'gridPager=' + JSON.stringify(data);
        this.jsonApiService.http("tunnelMarking/tunnelMarkingForPage.html", reqdata).subscribe(result => {
            if(result.isSuccess && result.exhibitDatas) {
                this.tableData = result.exhibitDatas;
                this.totalCount = result.recordCount;
            }
        });
    }
    // 添加隧道弹框
    tunnelMarkForm: any = {
        id: '',
        tunnelMarkName: '', // 隧道名称
        remark: '', // 隧道地址
        path: '', //覆盖物经纬度
    }
    pageType:string = '新增';
    addTunnelMark(modal) {
        $("#suggestId").val('');
        $("#inpLongitude").val('');
        $("#inpLatitude").val('');
        this.pageType = '新增';
        this.clearRailType3();
        this.tunnelMarkForm = {
            id: '',
            tunnelMarkName: '', // 隧道名称
            remark: '', // 隧道地址
            path: '', //覆盖物经纬度
        }
        this.MAP.clearOverlays();
        modal.show();
        
    }
    // 添加隧道提交
    tunnelMarkSubmit(modal) {
        if(!this.tunnelMarkForm.tunnelMarkName){
            this.jsonApiService.message('请输入隧道名称');
            return;
        }
        if(!this.tunnelMarkForm.path && !this.polygonData){
            this.jsonApiService.message('请绘制隧道标记位置');
            return;
        }
        let URL = 'tunnelMarking/addTunnelMarking.html';
        if(this.pageType == '编辑'){
            URL = 'tunnelMarking/editTunnelMarking';
        }
        var path = toWGS84Arr(this.polygonData||this.tunnelMarkForm.path);
        let reqData = {
            id: this.tunnelMarkForm.id,
            tunnelMarkName: this.tunnelMarkForm.tunnelMarkName,
            lnglats: JSON.stringify(path),
            remark: this.tunnelMarkForm.remark,
        }
        this.jsonApiService.http_obj(URL, reqData).subscribe(data => {
            this.jsonApiService.message(data.message);
            this.load();
            modal.hide();
            this.polygonDataBD = null;
            this.polygonData = null;
            this.isDrawing = false;
            this.drawingManager.close();
        })
    }
    // 添加隧道弹框关闭
    tunnelMarkClose(modal) {
        modal.hide();
    }
    // 编辑隧道
    editRow(row,modal) {
        $("#suggestId").val('');
        $("#inpLongitude").val('');
        $("#inpLatitude").val('');
        this.pageType = '编辑';
        modal.show(0);
        this.tunnelMarkForm = {
            id: row.id,
            tunnelMarkName: row.tunnelMarkName, // 隧道名称
            remark: row.remark, // 隧道地址
            path: JSON.parse(row.lnglats), //覆盖物经纬度
        }
        this.loadPath();
    }
    // 删除隧道
    deleteRow(row) {
        this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
            let parameters = {
                id: row.id,
            }
            this.jsonApiService.http_obj("tunnelMarking/deleteById.html", parameters).subscribe(data => {
                this.jsonApiService.message(data.message);
                this.load();
            })
        })
    }
    // 初始化地图
    MAP: any;
    mapSize:any = 14;
    mapMarker:any;
    initMap() {
        let that = this;
        var map = new BMap.Map("baiduMap", {
            enableMapClick: false
        });
        this.MAP = map;
        let point = new BMap.Point(116.404, 39.915); //创建点坐标
        map.centerAndZoom(point, this.mapSize); //初始化地图，设置中心点坐标和地图级别
        map.addEventListener("zoomend", function(){   
            that.mapSize = this.getZoom();
        });
        // var geolocation = new BMap.Geolocation();
        // geolocation.getCurrentPosition(function(r) {
        //     if(this.getStatus() == 0) {
        //         var mk = new BMap.Marker(r.point);
        //         map.panTo(r.point);
        //     }
        // }, {
        //     enableHighAccuracy: true
        // });
        map.enableScrollWheelZoom();
        this.initBmapAutoSearch(map);
    }
    // 百度地图自动检索功能
    initBmapAutoSearch(map) {
        //建立一个自动完成的对象
        let autoSearch = new BMap.Autocomplete({
            "input": "suggestId",
            "location": map
        });
        autoSearch.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件
            var str = "";
            var _value = e.fromitem.value;
            var value = "";
            if(e.fromitem.index > -1) {
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
            value = "";
            if(e.toitem.index > -1) {
                _value = e.toitem.value;
                value = _value.province + _value.city + _value.district + _value.street + _value.business;
            }
            str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
            document.getElementById("searchResultPanel").innerHTML = str;
        });
        let myValue;
        // 创建地址解析器实例
        var myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上,并调整地图视野
        autoSearch.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
            let _value = e.item.value;
            myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
            document.getElementById("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
            let local = new BMap.LocalSearch(map, { //智能搜索
                onSearchComplete: function(result) {
                    // var pp = result.getPoi(0).point;    //获取第一个智能搜索的结果
                    myGeo.getPoint(local.getResults().keyword, function(point) {
                        if(point) {
                            var pointNew = new BMap.Point(point.lng, point.lat);
                            if(this.mapMarker){
                               map.removeOverlay(this.mapMarker);
                               this.mapMarker = null;
                            }
                            this.mapMarker = new BMap.Marker(pointNew);        // 创建标注
                            this.MAP.addOverlay(this.mapMarker);
                            map.centerAndZoom(pointNew, this.mapSize);
                        } else {
                            alert("您选择地址没有解析到结果!");
                        }
                    }.bind(this), "深圳市");
                }.bind(this)
            });
            local.search(myValue);
        }.bind(this));
    }
    // 地图打点-渲染
    loadPath() {
        let that = this;
        let railStyle = {
            strokeColor:'#00c1de',
            fillColor:'red',
            strokeWeight:1,
            strokeOpacity:0.4,
            fillOpacity: 0.6,
            strokeStyle: 'solid'
        }
        this.MAP.clearOverlays();
        if(!this.tunnelMarkForm.path) return;
        var pathArr = [];
        var mapPointArr = toMapPointArr(this.tunnelMarkForm.path);
        if(!mapPointArr) {
            return;
        }
        if(mapPointArr.length > 0) {
            for(let j = 0; j < mapPointArr.length; j++) {
                pathArr.push(new BMap.Point(mapPointArr[j].lng, mapPointArr[j].lat));
            }
        }
        var myGraph = new BMap.Polygon(pathArr, railStyle); //创建多边形
//      this.polygonDataBD = myGraph;
        this.MAP.addOverlay(myGraph);
        let pp = myGraph.getBounds().getCenter();
        setTimeout(()=>{
            that.MAP.centerAndZoom(new BMap.Point(pp.lng, pp.lat),that.mapSize);
        },500)
    }
    suggestSearchBtn() {
        this.isDrawing = false;
        this.drawingManager.close();
        var that = this;
        if(!$("#suggestId").val()) {
            that.jsonApiService.message("请先输入地址");
            return;
        }
        that.MAP.clearOverlays();
        // 创建地址解析器实例
        var myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint($("#suggestId").val(), function(point) {
            if(point) {
                var pointNew = new BMap.Point(point.lng, point.lat);
                if(that.mapMarker){
                   that.MAP.removeOverlay(that.mapMarker);
                   that.mapMarker = null;
                }
                let marker = new BMap.Marker(pointNew);        // 创建标注
                that.MAP.addOverlay(marker);
                that.MAP.centerAndZoom(pointNew, that.mapSize);
            } else {
                alert("您选择地址没有解析到结果!");
            }
        }, "深圳市");
    }
    //自定义围栏画笔
    railTypeSelected(type) {
        if(this.isDrawing) {
            layer.msg('请先提交没有保存的多边形围栏', {
                icon: 0
            })
            return
        }
        this.drawingManager.open();
        this.drawingManager.setDrawingMode(type);
    }
    //清除围栏
    clearRailType3() {
        if(this.polygonDataBD) {
            this.MAP.removeOverlay(this.polygonDataBD);
        }
        this.polygonDataBD = null;
        this.polygonData = null;
        this.isDrawing = false;
        this.drawingManager.close();
    }
    drawingManager: any;
    polygonData: any;
    isDrawing: boolean = false;
    polygonDataBD: any;
    //初始化多边形绘画构造器
    initDrawingStyle() {
        var styleOptions = {
            strokeColor: "red", //边线颜色。
            fillColor: "#00c1de", //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 2, //边线的宽度，以像素为单位。
            strokeOpacity: 0.6, //边线透明度，取值范围0 - 1。
            fillOpacity: 0.6, //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
        }
        this.drawingManager = null;
        this.drawingManager = new BMapLib.DrawingManager(this.MAP, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: false, //是否显示工具栏
            circleOptions: styleOptions, //圆的样式
            polygonOptions: styleOptions, //多边形的样式
            rectangleOptions: styleOptions //矩形的样式
        });
        this.drawingManager.removeEventListener("overlaycomplete", function() {})
        this.drawingManager.addEventListener("overlaycomplete", function(e) {
            this.polygonData = null;
            this.polygonDataBD = null;
            this.polygonDataBD = e.overlay;
            this.polygonData = e.overlay.getPath();
            this.drawingManager.close();
            this.isDrawing = true;
//          let point = toWGS84(e.overlay.getBounds().getCenter());
//          let geo = new BMap.Geocoder();//坐标转换成实际地址
//          let pp = new BMap.Point(point.lng, point.lat);
//          geo.getLocation(pp, function(result) {
//              console.log(result,'result=================')
//          })
        }.bind(this))
    }
    // 根据经纬度进行定位
    inpMark(){
        this.isDrawing = false;
        this.drawingManager.close();
        let lng = $("#inpLongitude").val();
        let lat = $("#inpLatitude").val();
        if(lng&&lat){
            var new_point = new BMap.Point(lng,lat);
            if(this.mapMarker){
               this.MAP.removeOverlay(this.mapMarker);
               this.mapMarker = null;
            }
            this.mapMarker = new BMap.Marker(new_point);  // 创建标注
            this.MAP.addOverlay(this.mapMarker);              // 将标注添加到地图中
            this.MAP.panTo(new_point);
        }
    }
}